"use client";

import { Button, Pagination } from "antd";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import GoodCollectionError from "../../../components/GoodCollectionError";
import { GRADE_MAP, mockQuestions } from "./constant";
import "./index.css";

interface Question {
    id: number;
    labelNames: string[];
    subjectName: string;
    difficulty: number;
    subjectAnswer: string;
}

interface Props {
    params: {
        questionId: string;
    };
}

export default function BrushQuestions({ params }: Props) {
    const router = useRouter();
    const pathname = usePathname();
    const [question, setQuestion] = useState<Question | null>(null);
    const [currentIndex, setCurrentIndex] = useState(1);
    const [total, setTotal] = useState(mockQuestions.length);
    const [loading, setLoading] = useState(false);

    const fetchQuestion = async (pageIndex: number) => {
        setLoading(true);
        try {
            // 模拟 API 请求
            // const res = await req({
            //   method: 'post',
            //   data: {
            //     pageInfo: {
            //       pageIndex,
            //       pageSize: 1
            //     }
            //   },
            //   url: '/querySubjectInfo'
            // });

            // 使用 mock 数据
            const mockData = mockQuestions[pageIndex - 1];
            if (mockData) {
                setQuestion(mockData);
                setTotal(mockQuestions.length);
            }
        } catch (err) {
            console.error("获取题目失败:", err);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        // 从 URL 参数中获取题目 ID
        const questionId = parseInt(params.questionId);
        if (!isNaN(questionId)) {
            setCurrentIndex(questionId);
            fetchQuestion(questionId);
        }
    }, [params.questionId]);

    const handlePageChange = (page: number) => {
        setCurrentIndex(page);
        // 使用 replace 而不是 push，避免在历史记录中堆积
        router.replace(`/brushQuestions/${page}`);
    };

    const handlePrevQuestion = () => {
        if (currentIndex > 1) {
            const prevPage = currentIndex - 1;
            setCurrentIndex(prevPage);
            router.replace(`/brushQuestions/${prevPage}`);
        }
    };

    const handleNextQuestion = () => {
        if (currentIndex < total) {
            const nextPage = currentIndex + 1;
            setCurrentIndex(nextPage);
            router.replace(`/brushQuestions/${nextPage}`);
        }
    };

    return (
        <div className="brush-questions-box">
            <div className="question-box">
                <div className="question">
                    <div className="question-type">
                        <div className="number">{currentIndex}</div>
                        <div className="type">问答题</div>
                    </div>
                </div>
            </div>

            {question && (
                <>
                    <div className="question-content">
                        <div className="difficulty">
                            {GRADE_MAP[question.difficulty]}-
                            {question.labelNames.join("、")}
                        </div>
                        <div className="question-text">
                            {question.subjectName}
                        </div>
                    </div>

                    <div className="answer-box">
                        <div className="reference-answer">参考答案</div>
                        <div
                            className="answer-content wang-editor-style"
                            dangerouslySetInnerHTML={{
                                __html: question.subjectAnswer,
                            }}
                        />
                    </div>

                    <div className="change-question-box">
                        <GoodCollectionError id={question.id} />
                        <div className="navigation-buttons">
                            <Button
                                disabled={currentIndex <= 1}
                                onClick={handlePrevQuestion}
                                className="prev-button"
                            >
                                上一题
                            </Button>
                            <Button
                                disabled={currentIndex >= total}
                                onClick={handleNextQuestion}
                                className="next-button"
                            >
                                下一题
                            </Button>
                        </div>
                    </div>

                    {total > 0 && (
                        <div className="pagination-container">
                            <Pagination
                                current={currentIndex}
                                total={total}
                                pageSize={1}
                                onChange={handlePageChange}
                                showSizeChanger={false}
                            />
                        </div>
                    )}
                </>
            )}
        </div>
    );
}
